package com.yjyw.tiexie;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;

import com.yjyw.tiexie.activity.CheckPermissionActivity;
import com.yjyw.tiexie.activity.login.LoginActivity;
import com.yjyw.tiexie.adapter.VPFragmentAdapter;
import com.yjyw.tiexie.bean.AppUpdateBean;
import com.yjyw.tiexie.bean.MainChangeEvent;
import com.yjyw.tiexie.bean.event.HomeFragmentEvent;
import com.yjyw.tiexie.common.net.HandlerCode;
import com.yjyw.tiexie.common.net.NetCallBack;
import com.yjyw.tiexie.common.permission.IPermission;
import com.yjyw.tiexie.common.permission.PermissionManager;
import com.yjyw.tiexie.fragment.ActiveMainFragment;
import com.yjyw.tiexie.fragment.ContactsFragment;
import com.yjyw.tiexie.fragment.HomeFragment;
import com.yjyw.tiexie.fragment.MineFragment;
import com.yjyw.tiexie.util.ActivityManager;
import com.yjyw.tiexie.util.AppUtil;
import com.yjyw.tiexie.util.DownloadUtil;
import com.yjyw.tiexie.util.FastCilckOneUtil;
import com.yjyw.tiexie.util.GsonUtil;
import com.yjyw.tiexie.util.LogUtil;
import com.yjyw.tiexie.util.QMUIStatusBarHelper;
import com.yjyw.tiexie.util.SharedPreferencesUtils;
import com.yjyw.tiexie.util.StringUtil;
import com.yjyw.tiexie.util.update.NumberProgressBar;
import com.yjyw.tiexie.view.MyViewPager;
import com.yjyw.tiexie.view.QQNaviView;
import com.yjyw.tiexie.view.popupwindow.AppUpdateWindow;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.tencent.connect.share.QQShare;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;


public class MainActivity extends CheckPermissionActivity implements NetCallBack {
    @BindView(R.id.vp)
    MyViewPager vp;
    @BindView(R.id.tv_home)
    TextView tv_home;
    @BindView(R.id.tv_mine)
    TextView tv_mine;

    @BindView(R.id.tv_bottom_navigation_bar)
    TextView tv_bottom_navigation_bar;
    @BindView(R.id.tv_class)
    TextView tvClass;
    @BindView(R.id.tv_contacts)
    TextView tvContacts;
    @BindView(R.id.ll_bottom_menu)
    LinearLayout llBottomMenu;
    @BindView(R.id.iv_center)
    ImageView ivCenter;
    @BindView(R.id.rl_select)
    RelativeLayout rlSelect;
    @BindView(R.id.nv_home)
    QQNaviView nvHome;
    @BindView(R.id.nv_class)
    QQNaviView nvClass;
    @BindView(R.id.nv_contacts)
    QQNaviView nvContacts;
    @BindView(R.id.nv_mine)
    QQNaviView nvMine;

    private HomeFragment homeFragment;
    private ActiveMainFragment classFragment;
    private ContactsFragment contactsFragment;
    private MineFragment mineFragment;

    //下载工具类
    private DownloadUtil downloadUtil;
    //更新安装包地址
    private String url;
    //提示更新的dialog
    private Dialog reNameDialog;
    private AppUpdateWindow window;
    //下载的进度条
    private NumberProgressBar npb;

    private String urlName = "";
    private Uri apkUri;

    // 定义一个变量，来标识是否退出
    private static boolean isExit = false;
    //是否强更
    private boolean isForce = false;
    private static final int PHONE_REQUEST_CODE = 1002;
    private static final int GET_UNKNOWN_APP_SOURCES = 114;
    private int user_id;

    // user logged into another device
    public boolean isConflict = false;
    // user account was removed
    private boolean isCurrentAccountRemoved = false;


    private AlertDialog.Builder exceptionBuilder;
    private boolean isExceptionDialogShow = false;
    protected static final String TAG = "MainActivity";

    private int currentTabIndex;

    private int lastTabIndex = -1;//记录上次点的是哪个


    /**
     * check if current user account was remove
     */
    public boolean getCurrentAccountRemoved() {
        return isCurrentAccountRemoved;
    }

    @Override
    protected int getContentView() {
        return R.layout.activity_main;
    }

    @SuppressLint("HandlerLeak")
    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            isExit = false;
        }
    };

    @SuppressLint("HandlerLeak")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);


        window = new AppUpdateWindow();
        reNameDialog = new Dialog(this, R.style.Translucent_NoTitle);
        reNameDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);

        vpAddFragment();
        EventBus.getDefault().register(this);
        QMUIStatusBarHelper.immersive(this);
        QMUIStatusBarHelper.setStatusBarLightMode(this);

        SharedPreferences sp = getSharedPreferences("LoginState", 0);
        user_id = sp.getInt("user_id", 0);


        int young = (int) SharedPreferencesUtils.getParam(this, "isYoung", 0);
        if (young == 1) {
            EventBus.getDefault().post(new MainChangeEvent("1"));
        }


    }

    @Override
    protected void onPause() {
        super.onPause();
//        MobclickAgent.onPause(this);
    }


    @Override
    protected void onResume() {
        super.onResume();
        //这里防止按home键 出现多次弹框情况
        if (reNameDialog != null) {
            reNameDialog.dismiss();
        }
        //强制更新，防止下载后点击取消安装，再次检查版本号
        appUpdate();

        LogUtil.e("onResume", "onResume");
        //粘贴板记录
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();

        if (exceptionBuilder != null) {
            exceptionBuilder.create().dismiss();
            exceptionBuilder = null;
            isExceptionDialogShow = false;
        }


        if (mHandler != null) {
            mHandler.removeCallbacksAndMessages(null);
            mHandler = null;
        }
        if (handler != null) {
            handler.removeCallbacksAndMessages(null);
            handler = null;
        }
        if (reNameDialog != null) {
            reNameDialog.dismiss();
        }

        EventBus.getDefault().unregister(this);
    }


    /**
     * 实例化控件
     */
    @Override
    protected void init() {
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION, WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
        applyPermissionsLive();

    }

    private void applyPermissionsLive() {
        //获取短信权限基本联系人权限
        RxPermissions rxPermissions = new RxPermissions(this);
        rxPermissions
                .request(Manifest.permission.CAMERA, Manifest.permission.RECORD_AUDIO,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.READ_EXTERNAL_STORAGE)
                .subscribe(granted -> {
                    if (granted) {

                    } else {
                        //权限被拒绝
//                        showMissingPermissionDialog();
                    }
                });
    }


//    @IPermission(PHONE_REQUEST_CODE)
//    public void check() {
//        String[] perms = {Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA, Manifest.permission.RECORD_AUDIO, Manifest.permission.ACCESS_COARSE_LOCATION,};
//        if (PermissionManager.hasPermissions(this, perms)) {//授权通过
//
//        } else {//请求授权
//            PermissionManager.requestPermissions(this, PHONE_REQUEST_CODE, perms);
//        }
//    }


    /**
     * 版本更新
     */
    private void appUpdate() {//通过调个人信息接口，返回版本信息
//        HashMap map = new HashMap();
//        map.put("project_abbr", BuildConfig.MX_USER_TYPE);
//        post(map, NetAPI.GET_APP_VERSION, HandlerCode.GET_APP_VERSION, this);
    }


    /**
     * 给Viewpager添加Fragment
     */
    private void vpAddFragment() {
        int type = getIntent().getIntExtra("type", 0);
        List<Fragment> fgList = new ArrayList<>();
        //获得需要添加的Fragment
        classFragment = new ActiveMainFragment();
        homeFragment = new HomeFragment();
        contactsFragment = new ContactsFragment();
        mineFragment = new MineFragment();
        //将Fragment添加到集合中
        fgList.add(classFragment);
        fgList.add(homeFragment);
        fgList.add(contactsFragment);
        fgList.add(mineFragment);
        vp.setOffscreenPageLimit(3);
        FragmentManager fragmentManager = getSupportFragmentManager();//获得fragmentManager管理器
        vp.setAdapter(new VPFragmentAdapter(fragmentManager, fgList));//给ViewPager设置适配器
    }

    private void onChanged(int i) {
        switch (i) {
            case R.id.nv_home:
            case 0:
                if (lastTabIndex == 0) {
                    //再次点击 刷新视频
                    EventBus.getDefault().post(new HomeFragmentEvent("3"));
                    return;
                }
                //注意i 能是id值 currentTabIndex这里不要乱动
                currentTabIndex = 1;
                clear();
                nvHome.setBigIcon(R.drawable.main_home0);
                tv_home.setTextColor(ContextCompat.getColor(this, R.color.main_bottom_font_color02));
                vp.setCurrentItem(1);
                llBottomMenu.setBackgroundColor(getResources().getColor(R.color.black));
                lastTabIndex = 0;
                break;
            case R.id.nv_class:
            case 1:
                currentTabIndex = 0;
                clear();
                nvClass.setBigIcon(R.drawable.main_class0);
                tvClass.setTextColor(ContextCompat.getColor(this, R.color.main_bottom_font_color02));
                vp.setCurrentItem(0);
                llBottomMenu.setBackgroundColor(getResources().getColor(R.color.text_EEF1F8));
                lastTabIndex = 1;
                break;
            case R.id.nv_contacts:
            case 2:
                if (!SharedPreferencesUtils.isLogin(this)) {
                    //游客登录
                    startActivity(new Intent(this, LoginActivity.class));
                    return;
                }
                currentTabIndex = 2;
                clear();
                nvContacts.setBigIcon(R.drawable.main_contacts0);
                tvContacts.setTextColor(ContextCompat.getColor(this, R.color.main_bottom_font_color02));
                vp.setCurrentItem(2);
                llBottomMenu.setBackgroundColor(getResources().getColor(R.color.text_EEF1F8));
                lastTabIndex = 2;
                break;
            case R.id.nv_mine:
            case 3:
                if (!SharedPreferencesUtils.isLogin(this)) {
                    //游客登录
                    startActivity(new Intent(this, LoginActivity.class));
                    return;
                }
                currentTabIndex = 3;
                clear();
                nvMine.setBigIcon(R.drawable.main_me0);
                tv_mine.setTextColor(ContextCompat.getColor(this, R.color.main_bottom_font_color02));
                vp.setCurrentItem(3);
                llBottomMenu.setBackgroundColor(getResources().getColor(R.color.text_EEF1F8));
                lastTabIndex = 3;
                break;

            case R.id.rl_select:
                //选择类型弹框
                if (FastCilckOneUtil.isFastClick()) {
                    return;
                }
                if (!SharedPreferencesUtils.isLogin(this)) {
                    //游客登录
                    startActivity(new Intent(this, LoginActivity.class));
                    return;
                }
                //跳转二级页面选择
                break;
            default:
                break;
        }

    }

    /**
     * 点击后清除其他字体颜色
     */
    private void clear() {
        nvHome.setBigIcon(R.drawable.main_home1);
        nvClass.setBigIcon(R.drawable.main_class1);
        nvContacts.setBigIcon(R.drawable.main_contacts1);
        nvMine.setBigIcon(R.drawable.main_me1);
        tv_home.setTextColor(ContextCompat.getColor(this, R.color.main_bottom_font_color01));
        tvClass.setTextColor(ContextCompat.getColor(this, R.color.main_bottom_font_color01));
        tvContacts.setTextColor(ContextCompat.getColor(this, R.color.main_bottom_font_color01));
        tv_mine.setTextColor(ContextCompat.getColor(this, R.color.main_bottom_font_color01));
    }


    @Override
    protected void onStart() {
        super.onStart();
        applyPermissions();
    }

    private void applyPermissions() {
        //获取短信权限基本联系人权限
        RxPermissions rxPermissions = new RxPermissions(MainActivity.this);
        rxPermissions
                .request(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .subscribe(granted -> {
                    if (granted) {
                    } else {
                        //权限被拒绝
                        showMissingPermissionDialog();
                    }
                });
    }


    /**
     * 待封装
     *
     * @param updateContent
     * @param newVersion
     */
    private void showDialog(List<String> updateContent, String newVersion) {

        reNameDialog.show();

        reNameDialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
            @Override
            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_BACK) {
                    if (isForce) {//强制更新，按返回键不处理
                        return true;
                    } else {
                        reNameDialog.dismiss();
                    }
                }
                return false;
            }
        });

        window.intWindow(reNameDialog, updateContent, newVersion, isForce, url, this);

    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        LogUtil.e("onActivityResult", "从设置回来");
        switch (requestCode) {
            case GET_UNKNOWN_APP_SOURCES:
                LogUtil.e("onActivityResult", GET_UNKNOWN_APP_SOURCES + "");
//                AppUpdateWindow.getAppUpdateUtil().checkIsAndroidO(window.getApkUri(), this, window.getUrlName());
                LogUtil.e("checkIsAndroidO", "urlName:" + urlName);
                LogUtil.e("checkIsAndroidO", "apkUri:" + apkUri);
                AppUpdateWindow.getAppUpdateUtil().checkIsAndroidO(apkUri, this, urlName);
                break;
            default:
//                UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
                break;
        }
    }

    @OnClick({R.id.nv_home, R.id.nv_class, R.id.nv_contacts, R.id.nv_mine, R.id.rl_select})
    public void onViewClicked(View view) {
        onChanged(view.getId());
    }

    @Subscribe
    public void ChangeTab(MainChangeEvent mainChangeEvent) {
        if (StringUtil.isEmpty(mainChangeEvent.getType())) {
            if (handler != null) {
                Message message = handler.obtainMessage(1, mainChangeEvent.getIndex(), 0);
                message.sendToTarget();
            }
        } else {
            switch (mainChangeEvent.getType()) {
                case "2":
                    if (handler != null) {
                        Message message = handler.obtainMessage(3, 0, 0);
                        message.sendToTarget();
                    }
                    break;
                default:
                    break;
            }
        }
    }

    private int shareType = QQShare.SHARE_TO_QQ_TYPE_DEFAULT;
    private int mExtarFlag = 0x00;


    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    onChanged(msg.arg1);
                    break;
            }
        }
    };


    @Override
    public void onResponse(boolean flag, int requestCode, String result) throws Exception {
        switch (requestCode) {
            case HandlerCode.GET_APP_VERSION:
                AppUpdateBean appUpdateBean = (AppUpdateBean) GsonUtil.getObject(result, AppUpdateBean.class);
                if (appUpdateBean.getCode() == 200 && appUpdateBean.getData() != null) {
                    //先判断需不需要更新弹框
                    int is_update = appUpdateBean.getData().getIs_update();
                    if (is_update == 1) {//需要更新弹框，再判断code
                        int version_code = appUpdateBean.getData().getVersion_code();//从服务器获得APP最新版本号
                        if (version_code > AppUtil.getAppUtil().getAppVersionCode(this)) {
                            if (appUpdateBean.getData().getForced() == 0) {
                                isForce = false;
                            } else {
                                isForce = true;
                            }
                            url = appUpdateBean.getData().getHref();//下载地址
                            List<String> list = new ArrayList<>();
                            if (appUpdateBean.getData().getContent() != null) {
                                list.clear();
                                list.add(appUpdateBean.getData().getContent());
                            }
                            String newVersion = appUpdateBean.getData().getVersion() + "";//版本名字
                            showDialog(list, newVersion);
                        } else {
                            isForce = false;
                        }
                    }
                }
                break;
        }
    }


    private volatile int currentCode;

    @Override
    public void tokenTimeOut(int requestCode) {//重新获取token
        synchronized (this) {//保证currentCode对应当前线程的requestCode
//            currentCode = requestCode;
//            HashMap map = new HashMap();
//            map.put("clerkId", user_id);
//            get(map, NetAPI.UPDATE_TOKEN, HandlerCode.UPDATE_TOKEN, this);
        }
    }


    @Override
    public void onBackPressed() {
        if (isForce) {//如果是强制更新 禁止返回键
            return;
        } else {
            exit();
        }
    }


    private void exit() {
        if (!isExit) {
            isExit = true;
            Toast.makeText(getApplicationContext(), "再按一次退出程序",
                    Toast.LENGTH_SHORT).show();
            // 利用handler延迟发送更改状态信息
            mHandler.sendEmptyMessageDelayed(0, 2000);
        } else {
            finish();
            ActivityManager.getInstance().exit();
            System.exit(0);
        }
    }

}

